let db;
const dbName = 'PhoneDB';
const storeName = 'contacts';

// 初始化数据库和事件监听
document.addEventListener('DOMContentLoaded', () => {
// 初始化数据库
const request = indexedDB.open(dbName, 1);

request.onupgradeneeded = (event) => {
db = event.target.result;
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'name' });
}
};

request.onsuccess = (event) => {
db = event.target.result;
refreshContacts();
initEventListeners();
};

request.onerror = (event) => {
console.error('数据库打开失败:', event.target.error);
};
});

// 初始化事件监听
function initEventListeners() {
document.getElementById('addBtn').addEventListener('click', addContact);
document.getElementById('searchBtn').addEventListener('click', searchContact);
document.getElementById('deleteBtn').addEventListener('click', deleteContact);
document.getElementById('resetBtn').addEventListener('click', resetForm);
}

// 添加联系人
function addContact() {
const name = document.getElementById('nameInput').value.trim();
const phone = document.getElementById('phoneInput').value.trim();

if (!name || !phone) {
alert('姓名和电话不能为空');
return;
}

const transaction = db.transaction([storeName], 'readwrite');
const store = transaction.objectStore(storeName);

store.add({ name, phone }).onsuccess = () => {
refreshContacts();
resetForm();
};
}

// 查询联系人
function searchContact() {
const name = document.getElementById('nameInput').value.trim();
if (!name) return;

const transaction = db.transaction([storeName], 'readonly');
const store = transaction.objectStore(storeName);

store.get(name).onsuccess = (event) => {
const result = event.target.result;
document.getElementById('phoneInput').value = result ? result.phone : '';
};
}

// 删除联系人
function deleteContact() {
const name = document.getElementById('nameInput').value.trim();
if (!name) return;

const transaction = db.transaction([storeName], 'readwrite');
const store = transaction.objectStore(storeName);

store.delete(name).onsuccess = () => {
refreshContacts();
resetForm();
};
}

// 刷新通讯录显示（修改后）
function refreshContacts() {
const transaction = db.transaction([storeName], 'readonly');
const store = transaction.objectStore(storeName);
const contactsList = document.getElementById('contactsList');

store.getAll().onsuccess = (event) => {
const contacts = event.target.result;
// 添加固定标题行
const header = "姓名\t电话\n"; // 使用制表符对齐
const list = contacts.map(c => `${c.name}\t${c.phone}`).join('\n');
contactsList.value = header + list;

// 设置文本域最小高度（可选）
contactsList.style.minHeight = "200px";
};
}

// 重置表单
function resetForm() {
document.getElementById('nameInput').value = '';
document.getElementById('phoneInput').value = '';
}